package de.tuberlin.dima.dkey.examples;

import java.util.concurrent.BlockingQueue;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.google.gson.JsonParser;

import de.tuberlin.dima.dkey.client.Client;
import de.tuberlin.dima.dkey.client.GTree;
import de.tuberlin.dima.dkey.util.JsonTreeHelper;


public class SimpleGet {

	public static void main(String[] args) {

		//Set up the logging
		BasicConfigurator.configure();
		Logger.getRootLogger().setLevel(Level.ERROR);
		
		try {
			Client client = new Client("localhost", 8080);

			client.get(584719702);

			BlockingQueue<String> answer = client.getReturnQueue();
			
			JsonTreeHelper creator = new JsonTreeHelper();
			
	
			JsonParser parser = new JsonParser();
			try{
				String response = parser.parse(answer.take()).getAsJsonObject().get("response").toString();
				
				if(response.contains("error")){
					client.end();
					System.err.println(response);
					return;
				}
				
				if(response != null){
					GTree tree = new GTree(response);
				
					System.out.println("Json: " + creator.createJson(tree));
				}
			}catch(IllegalStateException e){
				System.out.println("JSon Parser Error: " + e);
				return;
			}
			


			//End everything
			client.end();


		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
